package com.joker.controller;

import com.joker.entity.Chat;
import com.joker.entity.ChatSession;
import com.joker.service.ChatService;
import com.joker.service.ChatSessionService;
import com.joker.utils.AnsjUtil;
import com.joker.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 聊天记录表 前端控制器
 * </p>
 *
 * @author joker
 * @since 2021-06-03
 */
@RestController
@RequestMapping("/chat")
@Api(value="ChatController",tags={"用户聊天记录操作接口"})
public class ChatHandler {

    @Autowired
    private ChatService chatService;

    @Autowired
    private ChatSessionService chatSessionService;
    /**
     * 更新聊天记录
     */
    @ApiOperation("更新未读聊天记录为已读")
    @GetMapping("/chatContext/{sessionId}")
    public ResultUtil chatContext(@PathVariable("sessionId")Integer sessionId){
        ChatSession chatSession = chatSessionService.findBySessionId(sessionId);
        //当未建立过会话连接，聊天记录为空，返回
        if (chatSession == null){
            return ResultUtil.error("连接记录为空");
        }
        //当已建立会话连接
        String userId = chatSession.getUserId();
        String toUserId = chatSession.getToUserId();
        //获取双方的聊天记录列表
        List<Chat> chatList = chatService.findByUserIdAndToUserId(userId,toUserId);
        if(chatList.size() != 0){
            //将聊天信息设置为已读
            chatService.setReadFlag(userId,toUserId);
            //重置会话表中的未读消息数
            Integer TorF = chatSessionService.setUnReadCount(userId,toUserId);
            if(TorF == 1){
                return ResultUtil.success(chatList,"更新成功");
            }
            return ResultUtil.error("重置聊天记录状态异常");
        }else {
            return ResultUtil.error("聊天记录为空");
        }
    }

    @ApiOperation("屏蔽敏感字符的聊天内容")
    @GetMapping("/checkChat/{context}")
    public ResultUtil testChat(@PathVariable("context") String context){
        return ResultUtil.success(AnsjUtil.parseStr(context));
    }

    @ApiOperation("删除双方的聊天记录")
    @DeleteMapping("/delete/{userId}/{toUserId}")
    public ResultUtil delete(@PathVariable("userId")String userId,@PathVariable("toUserId")String toUserId){
        Integer sum = chatService.delete(userId,toUserId);
        return ResultUtil.success(null,"成功删除了"+sum+"条聊天记录");
    }
}

